package com.jike.shop.cloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class RoutesConfig {

    @Autowired
    private KeyResolver hostAddrKeyResolver;

    @Autowired
    @Qualifier("userRateLimiter")
    private RateLimiter userRateLimiter;

    @Bean
    public RouteLocator declare(RouteLocatorBuilder builder) {
        return builder.routes()
                      .route(route -> route.path("/gateway/users/**")
                                           .filters(f -> f.stripPrefix(1)
                                                          .requestRateLimiter(limiter -> {
                                                                      limiter.setKeyResolver(hostAddrKeyResolver);
                                                                      limiter.setRateLimiter(userRateLimiter);
                                                                      limiter.setStatusCode(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED);
                                                                  }
                                                          )
                                           )
                                           .uri("lb://jike-user-service-server")
//                )
//                .route("id-001", route -> route
//                        // 在指定时间之前
//                        .before(ZonedDateTime.parse("2022-12-25T14:33:47.789+08:00"))
//                        // 在指定时间之后
//                        .or().after(ZonedDateTime.parse("2022-12-25T14:33:47.789+08:00"))
//                        // 或者在某个时间段以内
//                        .or().between(
//                                ZonedDateTime.parse("2021-12-25T14:33:47.789+08:00"),
//                                ZonedDateTime.parse("2022-12-25T14:33:47.789+08:00"))
//                        .uri("http://time.geekbang.org")
//                ).route(route -> route
//                        .path("/test/**")
//                        .uri("http://www.test.com")
                      ).build();

    }

}
